import { request } from '../utils/request';
import { User } from '../types/user';

// 路由常量
const AUTH_ROUTES = {
  LOGIN: '/auth/login',
  REGISTER: '/auth/register',
  VERIFY_EMAIL: '/auth/verify-email',
};

// 接口响应类型
export interface ApiResponse<T> {
  success: boolean;
  code: number;
  message: string;
  data: T;
  timestamp: string;
}

export interface AuthData {
  access_token: string;
  user: User;
}

export type AuthResponse = ApiResponse<AuthData>;

// 登录请求参数
interface LoginParams {
  username: string;
  password: string;
}

// 注册请求参数
interface RegisterParams {
  username: string;
  email: string;
  password: string;
}

// 邮箱验证响应
interface VerifyEmailResponse {
  message: string;
  status: 'verified' | 'already_verified' | 'error';
}

// 工具函数
export const setAuthData = (accessToken: string, user: User) => {
  localStorage.setItem('token', accessToken);
  localStorage.setItem('user', JSON.stringify(user));
};

export const clearAuthData = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
};

export const getStoredToken = () => {
  return localStorage.getItem('token');
};

export const getStoredUser = (): User | null => {
  const userStr = localStorage.getItem('user');
  if (userStr) {
    try {
      return JSON.parse(userStr);
    } catch (e) {
      console.error('解析用户数据失败:', e);
      return null;
    }
  }
  return null;
};

export const isAuthenticated = () => {
  return !!getStoredToken();
};

// 登录方法
export const login = async (params: LoginParams): Promise<AuthData> => {
  const response = await request.post<AuthResponse>('/auth/login', params);
  
  // 添加调试日志
  console.log('登录响应数据:', response);
  
  // 确保我们正确处理响应数据
  if (response.success && response.data && response.data.access_token && response.data.user) {
    console.log('验证通过，保存认证数据');
    setAuthData(response.data.access_token, response.data.user);
    return response.data;
  } else {
    console.error('数据格式验证失败:', {
      hasData: !!response.data,
      hasToken: !!(response.data && response.data.access_token),
      hasUser: !!(response.data && response.data.user)
    });
    throw new Error('登录响应数据格式错误');
  }
};

// 注册方法
export const register = async (params: RegisterParams): Promise<AuthData> => {
  const response = await request.post<AuthResponse>('/auth/register', params);
  
  if (response.success && response.data && response.data.access_token && response.data.user) {
    return response.data;
  } else {
    throw new Error('注册响应数据格式错误');
  }
};

// 获取当前登录用户信息
export const getCurrentUser = async (): Promise<User> => {
  const data = await request.get<User>('/auth/me');
  if (!data || !data.id) {
    throw new Error('获取用户信息失败');
  }
  return data;
};

// 退出登录
export const logout = () => {
  clearAuthData();
  window.location.href = AUTH_ROUTES.LOGIN;
};

// 验证邮箱
export const verifyEmail = async (token: string): Promise<VerifyEmailResponse> => {
  const data = await request.get<VerifyEmailResponse>('/auth/verify-email', { 
    params: { token } 
  });
  if (!data || !data.message) {
    throw new Error('邮箱验证响应数据格式错误');
  }
  return data;
};

export const authAPI = {
  login,
  register,
  verifyEmail,
  getCurrentUser,
  setAuthData,
  clearAuthData,
  getStoredToken,
  getStoredUser,
  isAuthenticated,
  logout
}; 